<script lang="ts" setup>
import type { SystemDeptApi } from '#/api/system/dept';
import type { SystemRoleApi } from '#/api/system/role';

import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { ElMessage, ElOption, ElSelect, ElTree } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { getDeptList, rootDept } from '#/api/system/dept';
import { assignRoleDataScope } from '#/api/system/permission';
import { getRole } from '#/api/system/role';
import { $t } from '#/locales';
import { SystemDataScopeEnum } from '#/utils/constants';
import { DICT_TYPE, getDictOptions } from '#/utils/dict';

import { useDataPermissionFormSchema } from '../data';

const emit = defineEmits(['success']);

const deptTreeRef = ref<InstanceType<typeof ElTree>>();

const deptTree = ref<SystemDeptApi.SystemDept[]>([]); // 部门树
const deptLoading = ref(false); // 加载部门列表
// const isAllSelected = ref(false); // 全选状态
// const isExpanded = ref(false); // 展开状态
// const isCheckStrictly = ref(true); // 父子联动状态
// const expandedKeys = ref<number[]>([]); // 展开的节点
const isShowToolBar = ref(false); // 部门树工具栏是否显示
const defaultExpandedKeys = ref<number[]>([]); // 默认展开
const defaultCheckedKeys = ref<number[]>([]); // 默认选中

const [Form, formApi] = useVbenForm({
  layout: 'horizontal',
  schema: useDataPermissionFormSchema(),
  showDefaultActions: false,
});
const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = await formApi.getValues();
    try {
      if (data.dataScope === SystemDataScopeEnum.DEPT_CUSTOM) {
        const dataTree = (deptTreeRef.value!.getCheckedKeys(false) ?? []).map(
          Number,
        );
        data.dataScopeDeptIds = dataTree;
      }
      await assignRoleDataScope({
        roleId: data.roleId,
        dataScope: data.dataScope,
        dataScopeDeptIds:
          data.dataScope === SystemDataScopeEnum.DEPT_CUSTOM
            ? data.dataScopeDeptIds
            : undefined,
      });
      await modalApi.close();
      emit('success');
      ElMessage.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.lock(false);
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      return;
    }
    const data = modalApi.getData<SystemRoleApi.SystemRole>();
    if (!data || !data.roleId) {
      return;
    }
    modalApi.lock();
    try {
      const roleData = await getRole(data.roleId as number);
      await formApi.setValues(roleData);

      // 加载部门列表
      await loadDeptTree();
      defaultCheckedKeys.value = roleData.dataScopeDeptIds;
    } finally {
      modalApi.lock(false);
    }
  },
});

/** 加载部门树 */
async function loadDeptTree() {
  deptLoading.value = true;
  try {
    const data = await getDeptList();
    rootDept.children = data;
    deptTree.value = [rootDept];
    getAllNodeIds(deptTree.value, defaultExpandedKeys.value);
  } finally {
    deptLoading.value = false;
  }
}
/** 全选/全不选
function toggleSelectAll() {
  isAllSelected.value = !isAllSelected.value;
  if (isAllSelected.value) {
    const allIds = getAllNodeIds(deptTree.value);
    formApi.setFieldValue('dataScopeDeptIds', allIds);
  } else {
    formApi.setFieldValue('dataScopeDeptIds', []);
  }
}*/
/** 展开/折叠所有节点
function toggleExpandAll() {
  isExpanded.value = !isExpanded.value;
  // 获取所有节点的 ID
  expandedKeys.value = isExpanded.value ? getAllNodeIds(deptTree.value) : [];
}
*/
/** 切换父子联动
function toggleCheckStrictly() {
  isCheckStrictly.value = !isCheckStrictly.value;
}
  */
/** 递归获取所有节点 ID */
function getAllNodeIds(nodes: any[], ids: number[] = []): number[] {
  nodes.forEach((node: any) => {
    ids.push(node.deptId);
    if (node.children && node.children.length > 0) {
      getAllNodeIds(node.children, ids);
    }
  });
  return ids;
}
function handleChange(value: number) {
  isShowToolBar.value = value === SystemDataScopeEnum.DEPT_CUSTOM;
}
</script>

<template>
  <Modal title="数据权限">
    <Form class="mx-4">
      <template #dataScope="slotProps">
        <ElSelect
          clearable
          placeholder="Select"
          v-bind="slotProps"
          @change="handleChange"
        >
          <ElOption
            v-for="item in getDictOptions(
              DICT_TYPE.SYSTEM_DATA_SCOPE,
              'number',
            )"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <span
              style="
                float: right;
                font-size: 13px;
                color: var(--el-text-color-secondary);
              "
            >
              {{ item.value }}
            </span>
          </ElOption>
        </ElSelect>
      </template>
      <template #dataScopeDeptIds="slotProps">
        <ElTree
          ref="deptTreeRef"
          :data="deptTree"
          show-checkbox
          node-key="deptId"
          :default-expanded-keys="defaultExpandedKeys"
          :default-checked-keys="defaultCheckedKeys"
          :props="slotProps"
        />
      </template>
    </Form>
    <template #prepend-footer>
      <div v-show="isShowToolBar" class="flex flex-auto items-center">
        <!-- <ElCheckbox :checked="isAllSelected" @change="toggleSelectAll">
          全选
        </ElCheckbox>
        <ElCheckbox :checked="isExpanded" @change="toggleExpandAll">
          全部展开
        </ElCheckbox>
        <ElCheckbox :checked="isCheckStrictly" @change="toggleCheckStrictly">
          父子联动
        </ElCheckbox> -->
      </div>
    </template>
  </Modal>
</template>
